package com.learn.bus.member;

import com.learn.bus.Data;
import com.learn.bus.Member;
import com.learn.bus.data.MessageData;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>项目名称: design-pattern </p>
 *
 * <p>文件名称: MessageCollectMember </p>
 *
 * Receiver of Data-Bus events that collects the messages from each {@link MessageData}.
 */
@Slf4j
public class MessageCollectMember implements Member {

    private final String name;

    private List<String> messages = new ArrayList<>();

    public MessageCollectMember(String name) {
        this.name = name;
    }

    @Override
    public void accept(Data data) {
        if (data instanceof MessageData) {
            handleEvent((MessageData) data);
            log.info(String.format("message %s", ((MessageData) data).getMessage()));
        }
    }

    private void handleEvent(MessageData data) {
        messages.add(data.getMessage());
    }

    public List<String> getMessages() {
        return Collections.unmodifiableList(messages);
    }
}
